import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 配置 NProgress
NProgress.configure({ 
  showSpinner: false,
  minimum: 0.2,
  easing: 'ease',
  speed: 500
})

// 路由配置
const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/Home/index.vue'),
    meta: {
      title: '首页',
      keepAlive: true,
      transition: 'fade'
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Auth/Login.vue'),
    meta: {
      title: '登录',
      hideNavbar: true,
      transition: 'slide-right'
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Auth/Register.vue'),
    meta: {
      title: '注册',
      hideNavbar: true,
      transition: 'slide-left'
    }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/views/Dashboard/index.vue'),
    meta: {
      title: '学习中心',
      requiresAuth: true,
      keepAlive: true,
      transition: 'fade'
    }
  },
  // 智能课堂模块
  {
    path: '/classroom',
    name: 'Classroom',
    component: () => import('@/views/Classroom/Layout.vue'),
    meta: {
      title: '智能课堂',
      requiresAuth: true
    },
    children: [
      {
        path: '',
        name: 'ClassroomHome',
        component: () => import('@/views/Classroom/Home.vue'),
        meta: { title: '课程首页', keepAlive: true }
      },
      {
        path: 'courses',
        name: 'CourseList',
        component: () => import('@/views/Classroom/CourseList.vue'),
        meta: { title: '课程列表', keepAlive: true }
      },
      {
        path: 'course/:id',
        name: 'CourseDetail',
        component: () => import('@/views/Classroom/CourseDetail.vue'),
        meta: { title: '课程详情' }
      },
      {
        path: 'course/:courseId/learn',
        name: 'CourseLearn',
        component: () => import('@/views/Classroom/Learn.vue'),
        meta: { title: '课程学习', fullscreen: true }
      },
      {
        path: 'course/:courseId/learn/:lessonId',
        name: 'LessonLearn',
        component: () => import('@/views/Classroom/Learn.vue'),
        meta: { title: '课时学习', fullscreen: true }
      },
      {
        path: 'study/:id',
        name: 'StudyRoom',
        component: () => import('@/views/Classroom/StudyRoom.vue'),
        meta: { title: '学习室', fullscreen: true }
      },
      {
        path: 'my-courses',
        name: 'MyCourses',
        component: () => import('@/views/Classroom/MyCourses.vue'),
        meta: { title: '我的课程', keepAlive: true }
      }
    ]
  },
  // 在线考试模块
  {
    path: '/exam',
    name: 'Exam',
    component: () => import('@/views/Exam/Layout.vue'),
    meta: {
      title: '在线考试',
      requiresAuth: true
    },
    children: [
      {
        path: '',
        name: 'ExamHome',
        component: () => import('@/views/Exam/Home.vue'),
        meta: { title: '考试首页', keepAlive: true }
      },
      {
        path: 'list',
        name: 'ExamList',
        component: () => import('@/views/Exam/ExamList.vue'),
        meta: { title: '考试列表', keepAlive: true }
      },
      {
        path: 'detail/:id',
        name: 'ExamDetail',
        component: () => import('@/views/Exam/ExamDetail.vue'),
        meta: { title: '考试详情' }
      },
      {
        path: ':examId/taking/:recordId',
        name: 'OnlineExam',
        component: () => import('@/views/Exam/OnlineExam.vue'),
        meta: { title: '在线考试', fullscreen: true }
      },
      {
        path: 'taking/:id',
        name: 'ExamTaking',
        component: () => import('@/views/Exam/ExamTaking.vue'),
        meta: { title: '正在考试', fullscreen: true }
      },
      {
        path: 'result/:id',
        name: 'ExamResult',
        component: () => import('@/views/Exam/ExamResult.vue'),
        meta: { title: '考试结果' }
      },
      {
        path: 'my-exams',
        name: 'MyExams',
        component: () => import('@/views/Exam/MyExams.vue'),
        meta: { title: '我的考试', keepAlive: true }
      }
    ]
  },
  // 编程实战模块
  {
    path: '/coding',
    name: 'Coding',
    component: () => import('@/views/Coding/Layout.vue'),
    meta: {
      title: '编程实战',
      requiresAuth: true
    },
    children: [
      {
        path: '',
        name: 'CodingHome',
        component: () => import('@/views/Coding/Home.vue'),
        meta: { title: '编程首页', keepAlive: true }
      },
      {
        path: 'problems',
        name: 'ProblemList',
        component: () => import('@/views/Coding/ProblemList.vue'),
        meta: { title: '题目列表', keepAlive: true }
      },
      {
        path: 'problem/:id',
        name: 'ProblemDetail',
        component: () => import('@/views/Coding/ProblemDetail.vue'),
        meta: { title: '题目详情' }
      },
      {
        path: 'editor/:id',
        name: 'CodeEditor',
        component: () => import('@/views/Coding/CodeEditor.vue'),
        meta: { title: '代码编辑器', fullscreen: true }
      },
      {
        path: 'submissions',
        name: 'MySubmissions',
        component: () => import('@/views/Coding/MySubmissions.vue'),
        meta: { title: '我的提交', keepAlive: true }
      },
      {
        path: 'leaderboard',
        name: 'Leaderboard',
        component: () => import('@/views/Coding/Leaderboard.vue'),
        meta: { title: '排行榜', keepAlive: true }
      }
    ]
  },
  // 学习任务模块
  {
    path: '/task',
    name: 'Task',
    component: () => import('@/views/Task/Layout.vue'),
    meta: {
      title: '学习任务',
      requiresAuth: true
    },
    children: [
      {
        path: '',
        name: 'TaskHome',
        component: () => import('@/views/Task/Home.vue'),
        meta: { title: '任务首页', keepAlive: true }
      },
      {
        path: 'list',
        name: 'TaskList',
        component: () => import('@/views/Task/TaskList.vue'),
        meta: { title: '任务列表', keepAlive: true }
      },
      {
        path: 'detail/:id',
        name: 'TaskDetail',
        component: () => import('@/views/Task/TaskDetail.vue'),
        meta: { title: '任务详情' }
      },
      {
        path: 'my-tasks',
        name: 'MyTasks',
        component: () => import('@/views/Task/MyTasks.vue'),
        meta: { title: '我的任务', keepAlive: true }
      },
      {
        path: 'create',
        name: 'TaskCreate',
        component: () => import('@/views/Task/TaskEditor.vue'),
        meta: { title: '创建任务' }
      },
      {
        path: 'edit/:id',
        name: 'TaskEdit',
        component: () => import('@/views/Task/TaskEditor.vue'),
        meta: { title: '编辑任务' }
      }
    ]
  },
  // 资讯中心模块
  {
    path: '/news',
    name: 'News',
    component: () => import('@/views/News/Layout.vue'),
    meta: {
      title: '资讯中心'
    },
    children: [
      {
        path: '',
        name: 'NewsHome',
        component: () => import('@/views/News/Home.vue'),
        meta: { title: '资讯首页', keepAlive: true }
      },
      {
        path: 'list',
        name: 'NewsList',
        component: () => import('@/views/News/NewsList.vue'),
        meta: { title: '资讯列表', keepAlive: true }
      },
      {
        path: 'detail/:id',
        name: 'NewsDetail',
        component: () => import('@/views/News/NewsDetail.vue'),
        meta: { title: '资讯详情' }
      }
    ]
  },
  // 图书馆模块
  {
    path: '/library',
    name: 'Library',
    component: () => import('@/views/Library/index.vue'),
    meta: {
      title: '图书馆',
      requiresAuth: true,
      keepAlive: true
    }
  },
  {
    path: '/library/book/:id',
    name: 'BookDetail',
    component: () => import('@/views/Library/BookDetail.vue'),
    meta: {
      title: '图书详情',
      requiresAuth: true
    }
  },
  {
    path: '/library/borrowings',
    name: 'BorrowingRecords',
    component: () => import('@/views/Library/BorrowingRecords.vue'),
    meta: {
      title: '借阅记录',
      requiresAuth: true
    }
  },
  {
    path: '/library/categories',
    name: 'LibraryCategories',
    component: () => import('@/views/Library/Categories.vue'),
    meta: {
      title: '图书分类',
      requiresAuth: true
    }
  },
  {
    path: '/library/category/:categoryId',
    name: 'CategoryBooks',
    component: () => import('@/views/Library/CategoryBooks.vue'),
    meta: {
      title: '分类图书',
      requiresAuth: true
    }
  },
  // AI聊天模块
  {
    path: '/ai-chat',
    name: 'AiChat',
    component: () => import('@/views/AiChat/index.vue'),
    meta: {
      title: 'AI助手',
      requiresAuth: true
    }
  },
  // 聊天模块
  {
    path: '/chat',
    name: 'Chat',
    component: () => import('@/views/Chat/index.vue'),
    meta: {
      title: '聊天室',
      requiresAuth: true
    }
  },
  // 文章模块
  {
    path: '/article',
    name: 'Article',
    component: () => import('@/views/Article/index.vue'),
    meta: {
      title: '文章中心',
      keepAlive: true
    }
  },
  {
    path: '/article/:id',
    name: 'ArticleDetail',
    component: () => import('@/views/Article/ArticleDetail.vue'),
    meta: {
      title: '文章详情'
    }
  },
  // 笔记模块
  {
    path: '/note',
    name: 'Note',
    component: () => import('@/views/Note/index.vue'),
    meta: {
      title: '我的笔记',
      requiresAuth: true,
      keepAlive: true
    }
  },
  {
    path: '/note/create',
    name: 'NoteCreate',
    component: () => import('@/views/Note/NoteEditor.vue'),
    meta: {
      title: '新建笔记',
      requiresAuth: true
    }
  },
  {
    path: '/note/:id',
    name: 'NoteDetail',
    component: () => import('@/views/Note/NoteDetail.vue'),
    meta: {
      title: '笔记详情',
      requiresAuth: true
    }
  },
  {
    path: '/note/:id/edit',
    name: 'NoteEdit',
    component: () => import('@/views/Note/NoteEditor.vue'),
    meta: {
      title: '编辑笔记',
      requiresAuth: true
    }
  },
  // 文档模块
  {
    path: '/document',
    name: 'Document',
    component: () => import('@/views/Document/index.vue'),
    meta: {
      title: '文档管理',
      requiresAuth: true,
      keepAlive: true
    }
  },
  {
    path: '/document/create',
    name: 'DocumentCreate',
    component: () => import('@/views/Document/DocumentEditor.vue'),
    meta: {
      title: '新建文档',
      requiresAuth: true
    }
  },
  {
    path: '/document/:id',
    name: 'DocumentDetail',
    component: () => import('@/views/Document/DocumentDetail.vue'),
    meta: {
      title: '文档详情',
      requiresAuth: true
    }
  },
  {
    path: '/document/:id/edit',
    name: 'DocumentEdit',
    component: () => import('@/views/Document/DocumentEditor.vue'),
    meta: {
      title: '编辑文档',
      requiresAuth: true
    }
  },
  {
    path: '/document/:id/versions',
    name: 'DocumentVersions',
    component: () => import('@/views/Document/DocumentVersions.vue'),
    meta: {
      title: '文档版本',
      requiresAuth: true
    }
  },
  // 版本控制模块
  {
    path: '/version',
    name: 'Version',
    component: () => import('@/views/Version/index.vue'),
    meta: {
      title: '版本控制',
      requiresAuth: true,
      keepAlive: true
    }
  },
  {
    path: '/version/repository/:id',
    name: 'RepositoryDetail',
    component: () => import('@/views/Version/RepositoryDetail.vue'),
    meta: {
      title: '仓库详情',
      requiresAuth: true
    }
  },
  {
    path: '/version/repository/:id/branches',
    name: 'RepositoryBranches',
    component: () => import('@/views/Version/RepositoryBranches.vue'),
    meta: {
      title: '分支管理',
      requiresAuth: true
    }
  },
  {
    path: '/version/repository/:id/commits',
    name: 'RepositoryCommits',
    component: () => import('@/views/Version/RepositoryCommits.vue'),
    meta: {
      title: '提交记录',
      requiresAuth: true
    }
  },
  // 商城模块
  {
    path: '/mall',
    name: 'Mall',
    component: () => import('@/views/Mall/index.vue'),
    meta: {
      title: '学习商城',
      keepAlive: true
    }
  },
  {
    path: '/mall/product/:id',
    name: 'ProductDetail',
    component: () => import('@/views/Mall/ProductDetail.vue'),
    meta: {
      title: '商品详情'
    }
  },
  {
    path: '/mall/cart',
    name: 'ShoppingCart',
    component: () => import('@/views/Mall/ShoppingCart.vue'),
    meta: {
      title: '购物车',
      requiresAuth: true
    }
  },
  {
    path: '/mall/orders',
    name: 'MyOrders',
    component: () => import('@/views/Mall/MyOrders.vue'),
    meta: {
      title: '我的订单',
      requiresAuth: true
    }
  },
  {
    path: '/mall/categories',
    name: 'MallCategories',
    component: () => import('@/views/Mall/Categories.vue'),
    meta: {
      title: '商品分类'
    }
  },
  {
    path: '/mall/category/:categoryId',
    name: 'CategoryProducts',
    component: () => import('@/views/Mall/CategoryProducts.vue'),
    meta: {
      title: '分类商品'
    }
  },
  // 网盘模块
  {
    path: '/disk',
    name: 'Disk',
    component: () => import('@/views/Disk/index.vue'),
    meta: {
      title: '云端网盘',
      requiresAuth: true,
      keepAlive: true
    }
  },
  // 用户中心
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/views/Profile/index.vue'),
    meta: {
      title: '个人中心',
      requiresAuth: true
    }
  },

  // 404 页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/Error/404.vue'),
    meta: {
      title: '页面未找到',
      hideNavbar: true
    }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else if (to.hash) {
      return { el: to.hash, behavior: 'smooth' }
    } else {
      return { top: 0, behavior: 'smooth' }
    }
  }
})

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  
  const userStore = useUserStore()
  const appStore = useAppStore()
  
  // 检查认证状态
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
    return
  }
  
  // 已登录用户访问登录页面，重定向到首页
  if ((to.name === 'Login' || to.name === 'Register') && userStore.isLoggedIn) {
    next('/')
    return
  }
  
  // 记录页面访问
  appStore.recordPageVisit(to.path)
  
  next()
})

// 全局后置守卫
router.afterEach((to, from) => {
  NProgress.done()
  
  // 更新页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - ZenithMind教育平台`
  }
})

export default router
